<template>
	<section>
		<!--工具条 高级查询 新增数据-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="query">
        <el-button type="danger" @click="batchRemove" :disabled="this.handleSelectValue.length===0">批量删除</el-button>
				<el-form-item>
					<el-input v-model="query.keyword" placeholder="请输入关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="search">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表 编辑 删除-->
		<el-table :data="pageInfo.rows" highlight-current-row v-loading="listLoading" @selection-change="handleSelectionChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="title" label="字典项目" width="200" sortable>
			</el-table-column>
			<el-table-column prop="intro" label="项目简介" width="200" sortable>
			</el-table-column>
			<el-table-column prop="sn" label="项目标识" width="200" sortable>
			</el-table-column>
			<el-table-column prop="status" label="状态" min-width="100" sortable>
        <template slot-scope="scope">
          <span v-if="scope.row.status == 1" style="color: green">正常</span>
          <span v-else style="color: red">禁用</span>
        </template>
			</el-table-column>
			<el-table-column label="操作" >
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
    </el-table>
		<!--工具条 批量删除 分页查询-->
		<el-col :span="24" class="toolbar">

      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="query.currentPage"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="query.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageInfo.total">
      </el-pagination>
		</el-col>
		<!--新增和修改模态框界面-->
		<el-dialog title="新增/修改" :visible.sync ="dictionaryFormVisible" :close-on-click-modal="false">
			<el-form :model="dictionaryForm" label-width="80px" :rules="addFormRules" ref="dictionaryForm">
				<el-form-item label="字典项目" prop="title">
					<el-input v-model="dictionaryForm.title" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="项目标识" prop="sn">
					<el-input v-model="dictionaryForm.sn" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="状态">
					<el-radio-group v-model="dictionaryForm.status">
						<el-radio class="radio" :label="1">正常</el-radio>
						<el-radio class="radio" :label="0">禁用</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="项目简介">
					<el-input type="textarea" v-model="dictionaryForm.intro"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="dictionaryFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="save" :loading="saveLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
	export default {
		data() {
			return {
				query: {
					currentPage: 1,
          pageSize: 10,
          keyword: ""
				},
				pageInfo: {
				  total: 0,//分页查询总条数
          rows: []//当前页展示数据
        },

				listLoading: false,//渲染列表页面时加载等待
        saveLoading: false,//保存页面时加载等待
				handleSelectValue: [],//里面装的是列表选中行的数据
				editFormRules: {//定义个规则:表示修改的时候这个属性是必须填写的
					title: [
						{ required: true, message: '请输入字典项目', trigger: 'blur' }
					],
					sn: [
						{ required: true, message: '请输入项目标识', trigger: 'blur' }
					]
				},
				dictionaryFormVisible: false,//新增/修改界面是否显示,模态框是否展示
				addFormRules: {
          title: [
            { required: true, message: '请输入字典项目', trigger: 'blur' }
          ],
          sn: [
            { required: true, message: '请输入项目标识', trigger: 'blur' }
          ]
				},
				//新增/修改界面数据
				dictionaryForm: {
				  id: null,
          sn: '',
          title: '',
          intro: '',
          status: null
				}
			}
		},
		methods: {
		  //关联删除方法
      deleteByParentId(parentId){
        //第一步：先获取parentId=当前字典的id
        this.$http.delete("/dictionaryitem/item/"+parentId)
            .then(result => {
              result=result.data;
              if (result.success){
                this.$message({
                  message: '删除成功'+result.message,
                  type: 'success'
                });
              }else {
                this.$message({
                  message: '删除失败'+result.message,
                  type: 'error'
                });
              }
            }).catch(result =>{
              this.$message({
              message: '前端删除失败',
              type: 'info'
          });
        })
      },
		  //高级查询，当输入关键字搜索时调用这个方法
      search(){
        this.query.currentPage=1;
        this.getDictionarys();
      },
      //当当前页改变时,来重新查取数据
			handleCurrentChange(val) {
				this.query.currentPage = val;
				this.getDictionarys();
			},
      //当当前页展示数据条数改变时，来重新查取数据
      handleSizeChange(val){
        //这里面带的参数就是当前页展示数据的条数
        this.query.pageSize=val;
        this.query.currentPage=1;
        this.getDictionarys();
      },
			//获取部门列表数据展示在页面
			getDictionarys() {
        //开始加载
				this.listLoading = true;
				this.$http.post("/dictionary",this.query)
            .then(result =>{
              //result中装的是从后端返回来的数据，是个分页高级查询返回的数据PageList{total: rows:[]}
              result = result.data;
              // console.log(result);
              if (result.success){
                this.pageInfo = result.result;
                this.listLoading = false;
              }else {
                this.$message({
                  message: '查询分页失败'+result.message,
                  type: 'error'
                });
              }
            })
            .catch(result => {
              this.$message({
                message: '查询分页失败,没有进入后端数据库',
                type: 'error'
              })
            })
			},
			//删除操作
			handleDel: function (index, row) {
        //index是选中的行的下标，row是选中行的数据，是个Object对象
        // console.log(row)
				this.$confirm('确认删除该记录吗?', '提示', {type: 'warning'})
            .then(() => {//点击确认进入这个then中
              this.listLoading = true;
              this.$http.delete("/dictionary/"+row.id)
                  .then(result =>{//与后端成功联通进入这个then
                    result = result.data;
                    if (result.success){
                      //当删除字典成功之后，将其对应的明细也删除
                      this.deleteByParentId(row.id);
                      this.query.currentPage = 1;
                      this.getDictionarys();
                      this.listLoading = false;
                    }else {
                      this.$message({
                        message: '删除失败'+result.message,
                        type: 'error'
                      });
                    }

                  })
				}).catch(result => {
          this.$message({
            message: '已取消删除',
            type: 'info'
          });
				});
			},
			//点击修改操作
			handleEdit: function (index, row) {
        //点击编辑按钮,弹出模态框,并回显编辑行的数据
				this.dictionaryFormVisible = true;
				//回显数据
				this.dictionaryForm = Object.assign({}, row);
				// debugger;
			},
			//点击新增操作
			handleAdd: function () {
        //点击新增按钮时弹出模态框
				this.dictionaryFormVisible = true;
				//初始化数据，因为是双向绑定的，避免值累积
				this.dictionaryForm = {
          id: null,
          sn: '',
          title: '',
          intro: '',
          status: null
				};
			},
			//新增和修改完了之后的保存方法
			save: function () {
				this.$refs.dictionaryForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.saveLoading = true;
							let para = Object.assign({}, this.dictionaryForm);
							this.$http.put("/dictionary",para)
                  .then(result => {
                    result = result.data;
                    if (result.success){
                      this.$message({
                        message: '提交成功'+result.message,
                        type: 'success'
                      });
                      this.dictionaryFormVisible = false;//关闭模态框
                      this.query.keyword=null;
                      this.query.currentPage = 1;//从第一页开始展示
                      this.getDictionarys();//重新查询列表数据
                      this.saveLoading = false;//关闭加载等待
                    }else {
                      this.$message({
                        message: '提交失败'+result.message,
                        type: 'error'
                      });
                    }
                  }).catch(result =>{
                this.$message({
                  message: '前端提交失败',
                  type: 'info'
                });
              })
						});
					}
				});
			},
      handleSelectionChange: function (rows) {
        // debugger;
        //rows是自带的一个参数，是个数组，里面装的是选中行的数据
				this.handleSelectValue = rows;
			},
			//批量删除
			batchRemove: function () {
         // debugger;
        //1先获取要删除的部门的id
        var ids =[];
				ids = this.handleSelectValue.map(dictionary => dictionary.id);
        //2.给出友情提示
				this.$confirm('确认删除选中记录吗？', '提示', {type: 'warning'})
            .then(() => {//用户点击确认就进入这个then
            this.listLoading = true;//渲染页面加载等待
            //发送请求到后端删除数据
              this.$http.patch("/dictionary",ids)
                  .then(result => {
                    result=result.data;
                    if (result.success){
                      this.$message({
                        message: '批量删除成功',
                        type: 'success'
                      });
                      //从第一页从新回显部门列表数据
                      this.query.currentPage=1;
                      this.getDictionarys();
                      this.listLoading=false//关闭加载
                    }else {
                      this.$message({
                        message: '批量删除失败'+result.message,
                        type: 'error'
                      });
                    }
                  })
				}).catch(result => {
          this.$message({
            message: '前端批量删除失败',
            type: 'error'
          });
				});
			}
		},
		mounted() {
			this.getDictionarys();
		}
	}
</script>
<style scoped>

</style>